package com.xyhuo.leetcode.january;

import com.xyhuo.leetcode.common.TreeNode;

/**
 * 验证二叉搜索树
 * https://leetcode.cn/problems/validate-binary-search-tree/
 *
 * @time 2024/1/5
 */
public class IsValidBST {

//    public static void main(String[] args) {
//        IsValidBST ivb = new IsValidBST();
//        TreeNode t1 = new TreeNode(1);
//        TreeNode t2 = new TreeNode(2);
//        TreeNode t3 = new TreeNode(3);
//        TreeNode t4 = new TreeNode(4);
//        TreeNode t5 = new TreeNode(5);
//        TreeNode t6 = new TreeNode(6);
//        t5.left = t1;
//        t5.right = t4;
//        t4.left = t3;
//        t4.right = t6;
//
//        ivb.isValidBST(t5);
//
//    }

    public boolean isValidBST(TreeNode root) {
        search(root);
        return ans;
    }

    private boolean ans = true;
    private Integer lastVal;

    private void search(TreeNode root) {
        if (!ans || null == root) {
            return;
        }
        search(root.left);
        if (null != lastVal && root.val <= lastVal) {
            ans = false;
            lastVal = root.val;
            return;
        }
        lastVal = root.val;
        search(root.right);
    }
}
